package com.haoxin.ai_course.task;

import java.io.FileNotFoundException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haoxin.ai_course.modules.course.biz.AcArticleBusiness;
import com.haoxin.ai_course.modules.course.entity.AcArticle;
import com.haoxin.ai_course.modules.course.mapper.AcArticleMapper;
import com.haoxin.ai_course.modules.course.service.AcArticleService;

import cn.hutool.core.collection.CollectionUtil;
@Service
@Component
public class FileUploadTask {
	@Autowired
	AcArticleMapper acArticleMapper;
	@Autowired
	AcArticleBusiness acArticleBusiness;
	@Autowired
	private AcArticleService acArticleService;
	@Value("${spring.article.UploadUrl}")
	String articleUploadUrl;
	@Value("${spring.article.filePath}")
	String filePath;
//	@Scheduled(cron = "* 0/10 * * * ?")
	public void uploadFile() {
		List<JSONObject> list = acArticleMapper.getUrls();
		if(CollectionUtil.isNotEmpty(list)) {
			List<String>fileIds = new ArrayList<String>();
			for (JSONObject jsonObject : list) {
				String fileId= jsonObject.getString("file_id");
				String fileName =	jsonObject.getString("file_name");
				String file_path =jsonObject.getString("file_path");
		        String url = articleUploadUrl+fileName;
		        if(isConnect(url)) {
		        	fileIds.add(fileId);
		        	acArticleService.updateFilePath(fileId, url);
		        	continue;
		        }
				try {
					acArticleBusiness.uploadVideo(fileId, fileName, file_path);
			        if(isConnect(url)) {
			        	fileIds.add(fileId);
			        	acArticleService.updateFilePath(fileId, url);
			        }
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
			if(CollectionUtil.isNotEmpty(fileIds)) {
				QueryWrapper<AcArticle> qw = new QueryWrapper<AcArticle>();
				qw.lambda().eq(AcArticle::getUploadStatus,  0);
				qw.lambda().in(AcArticle::getFileId, fileIds);
				List<AcArticle>list1 = acArticleService.list(qw);
				if(CollectionUtil.isNotEmpty(list1)) {
					for (AcArticle acArticle : list1) {
						acArticle.setUploadStatus(1);
					}
					acArticleService.updateBatchById(list1);
				}
			}
		}
	}
	
	 /** 
	   * 功能：检测当前URL是否可连接或是否有效, 
	   * 描述：最多连接网络 5 次, 如果 5 次都不成功，视为该地址不可用 
	   * @param urlStr 指定URL网络地址 
	   * @return URL 
	   */  
	public synchronized Boolean isConnect(String urlStr) {  
		  URL url  = null;  
		  HttpURLConnection con;  
		  int state = -1;
	   int counts = 0;  
	   if (urlStr == null || urlStr.length()== 0) {                         
	    return null;                   
	   }  
	    try {  
	     url = new URL(urlStr);  
	     con = (HttpURLConnection) url.openConnection();  
	     state = con.getResponseCode();  
	     System.out.println(counts +"= "+state);  
	     if (state == 200) {  
	      System.out.println("URL可用！");  
	     }  
	    }catch (Exception ex) {  
	     counts++;   
	     System.out.println("URL不可用，连接第 "+counts+" 次");  
	     urlStr = null;  
	    }  
	   return url == null;  
	}  
}
